import axios from 'axios'
import router from '../router'
import { Toast, Indicator } from 'mint-ui';
import qs from 'qs'
import { encrypting, api , is_weixin } from '../config';
//加密

axios.defaults.timeout = 100000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.baseURL = api;
axios.interceptors.request.use((config) => {
	Indicator.open({
		text: '加载中...',
		spinnerType: 'fading-circle'
	});

	if(config.method === 'post') {
		let a = "&"
		for(var i in config.data) {
			a += i + "=" + config.data[i] + "&"
		}
		config.data = encrypting(a)
	}
	return config;
}, (error) => {
	return Promise.reject(error);
});

// http response 拦截器
axios.interceptors.response.use(
	response => {
		let msg = response.data.msg;
		if(response.data.code == '416') {
			if(is_weixin()) {
				router.replace({
					path: '/wecateLogin',
					query: {
						redirect: router.currentRoute.fullPath
					}
				})
			} else {
				router.replace({
					path: '/smsLogin',
					query: {
						redirect: router.currentRoute.fullPath
					}
				})
			}
			localStorage.removeItem('token')
			localStorage.removeItem('member')
		}
		Indicator.close();
		return response;

	},
	error => {
		if(error.response) {

		}
		Toast({
			message: '网络错误',
			position: 'bottom',
			duration: 2000
		})
		Indicator.close();
		return Promise.reject(error.response.data)
	});

//返回一个Promise(发送post请求)
export function fetch(url, params) {
	return new Promise((resolve, reject) => {
		axios.post(url, params)
			.then(response => {
				resolve(response.data);
			}, err => {
				reject(err);
			})
			.catch((error) => {
				reject(error)
			})
	})
}

//返回一个Promise(发送post请求)
export function bind() {
	return new Promise((resolve, reject) => {
		axios.post('/api/fg/isBoolean', {
				token: localStorage.getItem('token'),
				loginType: localStorage.getItem('loginType')
			})
			.then(response => {
				resolve(response.data.obj.boolean);
			}, err => {
				reject(err);
			})
			.catch((error) => {
				reject(error)
			})
	})
}